/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chatclient;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author isen
 */
public class ChatLogic {

    ChatInterface gui;
    ServerConnection server;
    int currentConversation = -1;
    boolean loggedIn = false;
    String loggedInAs;

    public void start() {
        try {
            server = new ServerConnection("localhost", 8091);
            Scanner in = new Scanner(System.in);
            for (int j=0; j<3 && !loggedIn;j++) {
                System.out.println("login or create new account?");
                String firstAction = in.nextLine();

                if (firstAction.equals("login")) {
                    for (int i = 0; i < 3 && !loggedIn; i++) {
                        System.out.println("Enter your username: ");
                        String username = in.nextLine();
                        System.out.println("Enter your password: ");
                        String password = in.nextLine();
                        loggedIn = server.login(username, password);
                        if (!loggedIn) {
                            System.out.println("Wrong username/password combination.");
                        } else {
                            loggedInAs = username;
                        }
                    }
                } else if (firstAction.equals("create")) {
                    String username;
                    boolean exists = false;
                    do {
                        if (exists) {
                            System.out.println("Username already used.");
                        }
                        System.out.println("Enter your username:");
                        username = in.nextLine();
                        exists = server.usernameExists(username);
                    } while (exists);
                    System.out.println("Enter your name:");
                    String name = in.nextLine();
                    System.out.println("Enter your email:");
                    String email = in.nextLine();
                    System.out.println("Enter your password:");
                    String password = in.nextLine();
                    System.out.println("Confirm your password:");
                    String confirmpassword = in.nextLine();
                    if (password.equals(confirmpassword)) {
                        server.createAccount(username, password, name, email);
                        loggedIn = server.login(username, password);
                        if (!loggedIn) {
                            System.out.println("Wrong username/password combination.");
                        } else {
                            loggedInAs = username;
                        }
                    } else {
                        System.out.println("passwords do not match");
                    }
                }
            }

            if (loggedIn) {
                gui = new ChatInterface(ChatLogic.this);
                gui.setVisible(true);
                gui.addLine("Logged in as " + loggedInAs);
                new Thread() {

                    @Override
                    public void run() {
                        String line;
                        while (server.isConnected()) {
                            line = server.readLine();
                            if (line == null) {
                                gui.addLine("Connection to Server lost.");
                                break;
                            }
                            serverInput(line);
                        }
                    }
                }.start();
            }
        } catch (UnknownHostException ex) {
            Logger.getLogger(ChatLogic.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ChatLogic.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    void userInput(String input) {
        if (input.startsWith("/")) {
            invokeCommand(input.substring(1));
        } else {
            invokeCommand("message " + currentConversation + " " + input);
        }
    }

    void serverInput(String commandSequence) {
        int pos = commandSequence.indexOf(" ");
        String arguments = pos == -1 ? "" : commandSequence.substring(pos + 1);
        String command = pos == -1 ? commandSequence : commandSequence.substring(0, pos);
        System.out.println("server: " + commandSequence);

        if (command.equals("userlist")) {
            gui.addLine(" " + arguments);
        } else if (command.equals("startConversation")) {
            gui.addLine("Conversation request: ");
            gui.addLine(arguments);
        } else if (command.equals("youStarted")) {
            switchConversation(Integer.parseInt(arguments));
        } else if (command.equals("message")) {
            gui.addLine(arguments);
        } else if (command.equals("conversationslist")) {
            gui.addLine(" " + arguments);
        } else if (command.equals("history")) {
            gui.addLine(arguments);
        } else {
            gui.addLine("server: " + commandSequence);
        }
    }

    void switchConversation(int conversation) {
        currentConversation = conversation;
        gui.addLine("You are now in conversation " + conversation);
    }

    void invokeCommand(String commandSequence) {
        int pos = commandSequence.indexOf(" ");
        String arguments = pos == -1 ? "" : commandSequence.substring(pos + 1);
        String command = pos == -1 ? commandSequence : commandSequence.substring(0, pos);
        System.out.println("user: " + commandSequence);


        if (command.equals("quit")) {
            gui.dispose();
            server.writeLine("quit");
        } else if (command.equals("listusers")) {
            gui.addLine("List of online users: ");
            server.writeLine("listusers");
        } else if (command.equals("listconversations")) {
            gui.addLine("List of Conversations: ");
            server.writeLine("listconversations");
        } else if (command.equals("switch")) {
            switchConversation(Integer.parseInt(arguments));
        } else if (command.equals("leave")) {
            if (!arguments.isEmpty()) {
                server.writeLine("leave " + arguments);
            } else if (currentConversation != -1) {
                server.writeLine("leave " + currentConversation);
            } else {
                gui.addLine("No conversation selected to leave.");
            }
        } else if (command.equals("start")) {
            server.writeLine("start " + arguments);
        } else if (command.equals("accept")) {
            server.writeLine("accept " + arguments);
            switchConversation(Integer.parseInt(arguments));
        } else if (command.equals("history")) {
            if (!arguments.isEmpty()) {
                server.writeLine("history " + arguments);
            } else if (currentConversation != -1) {
                server.writeLine("history " + currentConversation);
            } else {
                gui.addLine("No conversation selected to show history.");
            }
        } else if (command.equals("message")) {
            int spacePos = arguments.indexOf(" ");
            int conversation = Integer.parseInt(arguments.substring(0, spacePos));
            String message = arguments.substring(spacePos + 1);
            if (conversation != -1) {
                server.writeLine("message " + conversation + " " + message);
            } else {
                gui.addLine("No conversation selected.");
            }
        } else {
            gui.addLine("wrong command.");
        }
    }
}
